import { createRouter, createWebHistory } from 'vue-router'
import useUserStore from '@/stores/user'
import usePermissionStore from '@/stores/permission'
import HomeView from '../views/HomeView.vue'
import Layout from '../layout/index.vue'
// 公用路由
export const constantRoutes = [
  {
    path: '/login',
    name: 'login',
    meta: {
      title: '登录系统'
    },
    component: () => import('../views/Login.vue')
  },
  {
    path: '/',
    redirect: '/dashboard',
    component: Layout,
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        meta: {
          title: '系统首页',
          icon: 'homepage'
        },
        component: HomeView
      }
    ]
  },
  {
    path: '/dp/main',
    name: 'dpMain',
    component: () => import('../views/dpMain/IndexView.vue')
  }
]

const dynamicRoutes: any = []

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...constantRoutes]
})

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  const permissionStore = usePermissionStore()
  // 处理登录页的特殊情况
  if (to.path == '/login') {
    userStore.logOut()
    next()
    return
  }

  if (!userStore.token) {
    next('/login')
    return
  }

  // 已经添加动态路由直接放行
  // TODO: 需要注意的就是添加路由是异步的，next方法是同步的，如果添加后变直接next(),那么刷新页面会导致路由还没正确添加，从而导致路由跳转失败
  if (permissionStore.routesAdded) {
    next()
  } else {
    try {
      if (userStore.token) {
        const accessRoutes = await permissionStore.generateRoutes([])
        accessRoutes.forEach((route) => {
          router.addRoute(route)
        })
        // 设置已添加动态路由
        permissionStore.setRoutesAdded(true)
      }
      next({ ...to, replace: true })
    } catch (error) {
      // 处理错误
      userStore.logOut()
      next('/login')
    }
  }
})

export default router
